<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */
namespace app\admin\controller;

use think\Db;
use think\Page;
use think\Cache;
use app\common\logic\NavigationLogic;

class Pc extends Base
{
    // 系统默认位置ID，不可删除
    private $ad_position_system_id = [];

    /**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();
        // 当前时间戳
        $this->times = getTime();
        $this->navigationlogic = new NavigationLogic;
    }

    public function index()
    {
        return $this->fetch();
    }

    // 基础设置
    public function settings($pages = '', $attr_id = 0)
    {
        // 查询原配置信息
        $inc_type =  'web';
        $config = tpCache($inc_type);
        $this->assign('config', $config);

        if (IS_AJAX_POST && empty($pages)) {
            $param = input('post.');
            // 特定处理
            $param['web_keywords'] = str_replace('，', ',', htmlspecialchars_decode($param['web_keywords']));
            $param['web_description'] = filter_line_return($param['web_description']);

            // 正则去除JS标签代码
            $param = removeJsTagCode($param);

            // 网站根网址
            $web_basehost = rtrim($param['web_basehost'], '/');
            if (!is_http_url($web_basehost) && !empty($web_basehost)) $web_basehost = $this->request->scheme().'://'.$web_basehost;
            $param['web_basehost'] = $web_basehost;

            // 浏览器地址图标
            if (!empty($param['web_ico']) && !is_http_url($param['web_ico'])) {
                $source = realpath(preg_replace('#^'.$this->root_dir.'/#i', '', $param['web_ico']));
                $destination = realpath('favicon.ico');
                if (empty($destination) || $source == $destination) {
                    unset($param['web_ico']);
                } else {
                    // 修复copy一句话图片木马漏洞
                    $image_ext = config('global.image_ext');
                    $image_ext_arr = explode(',', $image_ext);
                    $source_ext = pathinfo($source, PATHINFO_EXTENSION);
                    if (!empty($source_ext) && !in_array($source_ext, $image_ext_arr)) $this->error('地址栏图标必须是ico扩展名的图片');
                    if (file_exists($source) && @copy($source, $destination)) $param['web_ico'] = $this->root_dir.'/favicon.ico';
                }
            }

            // 保存更新配置
            tpCache($inc_type, $param);

            // 写入全局内置参数
            write_global_params();

            // 更换域名则查询域名是否授权
            if ($config['web_basehost'] != $param['web_basehost']) verify_authortoken();

            // 返回结束
            $this->success('操作成功');
        }

        if (!empty($attr_id)) {
            // 查询指定自定义字段
            $where = [
                'a.attr_id' => intval($attr_id),
                'a.release_field' => 0,
            ];
        } else {
            $where = [
                'b.is_del' => 0,
                'a.release_field' => 1,
            ];
            // 查询字段列表
            $attr_var_names = Db::name('config')->where(['name' => ['LIKE', "pc_web_attr_%"], 'is_del' => 0])->column('name');
            if (!empty($attr_var_names)) $where['a.attr_var_name'] = ['IN', array_keys($attr_var_names)];
        }
        // 查询字段列表
        $configList = Db::name('config_attribute')->alias('a')
            ->field('a.*, b.id, b.value')
            ->join('__CONFIG__ b', 'b.name = a.attr_var_name', 'LEFT')
            ->where($where)
            ->order('a.sort_order asc, a.attr_id asc')
            ->select();
        foreach ($configList as $key => $value) {
            $value['id'] = !empty($value['id']) ? trim($value['id']) : 0;
            $value['value'] = !empty($value['value']) ? trim($value['value']) : '';
            // 如果是图片则执行图片处理
            if (3 === intval($value['attr_input_type'])) $value['value'] = handle_subdir_pic($value['value']);
            // 调用字段名
            $value['attr_var_title'] = str_replace('pc_web_attr_', 'pc_web_attrname_', $value['attr_var_name']);
            $configList[$key] = $value;
        }
        // dump($configList);exit;

        $this->assign('configList', $configList);
        return $this->fetch(!empty($pages) ? $pages : '');
    }

    public function settings_add()
    {

        return $this->fetch();
    }

    public function settings_edit()
    {

        return $this->fetch();
    }

    // 广告管理
    public function avd_index()
    {
        // 应用搜索条件
        $where = [];
        $get = input('get.');
        foreach (['keywords', 'type'] as $key) {
            $get[$key] = addslashes(trim($get[$key]));
            if (!empty($get[$key])) {
                if ($key == 'keywords') {
                    $where['title'] = ['LIKE', "%{$get[$key]}%"];
                } else {
                    $where[$key] = ['eq', $get[$key]];
                }
            }
        }
        $count = Db::name('ad_position')->where($where)->count();
        $Page = new Page($count, config('paginate.list_rows'));
        $list = Db::name('ad_position')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->getAllWithIndex('id');

        // 每组获取三张图片
        $pids = get_arr_column($list, 'id');
        $ad = Db::name('ad')->where(['pid' => ['IN', $pids]])->order('pid asc, id asc')->select();
        foreach ($list as $key => $value) {
            if (1 === intval($value['type'])) {
                // 图片封面图片
                $value['ad'] = [];
                foreach ($ad as $m => $n) {
                    if ($value['id'] == $n['pid']) {
                        $n['litpic'] = get_default_pic($n['litpic']); // 支持子目录
                        $value['ad'][] = $n;
                        unset($ad[$m]);
                    } else {
                        continue;
                    }
                }
                // 若没有内容则显示默认图片
                if (empty($value['ad'])) {
                    $value['ad_count'] = 0;
                    $value['ad'][]['litpic'] = ROOT_DIR . '/public/static/common/images/not_adv.jpg';
                } else {
                    $value['ad_count'] = count($value['ad']);
                }
                // 广告类型
                $value['type_name'] = '图片';
            }
            else if (2 === intval($value['type'])) {
                // 多媒体封面图片
                $value['ad'][]['litpic'] = ROOT_DIR . '/public/static/admin/images/ad_type_media.png';
                // 广告类型
                $value['type_name'] = '多媒体';
            }
            else if (3 === intval($value['type'])) {
                // HTML代码封面图片
                $value['ad'][]['litpic'] = ROOT_DIR . '/public/static/admin/images/ad_type_html.png';
                // 广告类型
                $value['type_name'] = 'HTML代码';
            }
            $list[$key] = $value;
        }

        $this->assign('page', $Page->show());
        $this->assign('list', $list);
        $this->assign('pager', $Page);
        return $this->fetch();
    }

    // 广告添加
    public function avd_add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 请填写广告名称
            if (empty($post['title'])) $this->error('请填写广告名称');
            // 查询是否存在重名广告
            if (Db::name('ad_position')->where(['title' => trim($post['title'])])->count() > 0) $this->error('该广告名称已存在，请检查');

            // 添加广告位置表信息
            $insert = [
                'title' => trim($post['title']),
                'type'  => !empty($post['type']) ? intval($post['type']) : 1,
                'intro' => !empty($post['intro']) ? strval($post['intro']) : '',
                'admin_id' => session('admin_id'),
                'add_time' => $this->times,
                'update_time' => $this->times,
            ];
            $insertID = Db::name('ad_position')->insertGetId($insert);
            if (!empty($insertID)) {
                // 读取组合广告位的图片及信息
                $insertAll = [];
                // 图片类型
                if (1 === intval($post['type']) && !empty($post['img_litpic'])) {
                    $i = 1;
                    foreach ($post['img_litpic'] as $key => $value) {
                        if (!empty($value)) {
                            // 添加参数
                            $insertAll[] = [
                                // 主要参数
                                'litpic' => preg_replace('/https:|http:|\s+/i', '', $value),
                                'pid'    => intval($insertID),
                                'title'  => !empty($post['img_title'][$key]) ? trim($post['img_title'][$key]) : '',
                                'links'  => !empty($post['img_links'][$key]) ? trim($post['img_links'][$key]) : '',
                                'intro'  => !empty($post['img_intro'][$key]) ? trim($post['img_intro'][$key]) : '',
                                'target' => !empty($post['img_target'][$key]) ? 1 : 0,
                                // 其他参数
                                'media_type'  => 1,
                                'admin_id'    => session('admin_id'),
                                'sort_order'  => $i++,
                                'add_time'    => $this->times,
                                'update_time' => $this->times,
                            ];
                        }
                    }
                }
                // 媒体类型
                else if (2 === intval($post['type']) && !empty($post['video_litpic'])) {
                    // 添加参数
                    $insertAll[] = [
                        // 主要参数
                        'litpic' => preg_replace('/https:|http:|\s+/i', '', $post['video_litpic']),
                        'pid'    => intval($insertID),
                        'title'  => !empty($post['title']) ? trim($post['title']) : '',
                        'links'  => '',
                        'intro'  => '',
                        'target' => 0,
                        // 其他参数
                        'media_type'  => 2,
                        'admin_id'    => session('admin_id'),
                        'sort_order'  => 1,
                        'add_time'    => $this->times,
                        'update_time' => $this->times,
                    ];
                }
                // HTML代码
                else if (3 === intval($post['type']) && !empty($post['html_intro'])) {
                    // 添加参数
                    $insertAll[] = [
                        // 主要参数
                        'litpic' => '',
                        'pid'    => intval($insertID),
                        'title'  => !empty($post['title']) ? trim($post['title']) : '',
                        'links'  => '',
                        'intro'  => !empty($post['html_intro']) ? trim($post['html_intro']) : '',
                        'target' => 0,
                        // 其他参数
                        'media_type'  => 3,
                        'admin_id'    => session('admin_id'),
                        'sort_order'  => 1,
                        'add_time'    => $this->times,
                        'update_time' => $this->times,
                    ];
                }
                // 批量新增
                $result = !empty($insertAll) ? Db::name('ad')->insertAll($insertAll) : false;
                if (!empty($result)) {
                    Cache::clear('ad');
                    adminLog('新增广告：'. $post['title']);
                }
                $this->success("操作成功", url('Pc/avd_index'));
            }

            $this->error("操作失败");
        }

        // 视频类型
        $media_type = tpCache('global.media_type');
        $media_type = !empty($media_type) ? $media_type : config('global.media_ext');
        $media_type = str_replace(",", "|", $media_type);
        $this->assign('media_type', $media_type);

        // 系统最大上传视频的大小
        $this->assign('upload_max_filesize', upload_max_filesize());

        return $this->fetch();
    }

    // 广告编辑
    public function avd_edit()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            if (!empty($post['id'])) {
                $post['id'] = intval($post['id']);
                // 不可更改系统预定义位置
                if (array_key_exists($post['id'], $this->ad_position_system_id)) $this->error("不可更改系统预定义位置");
                // 请填写广告名称
                if (empty($post['title'])) $this->error('请填写广告名称');
                // 查询是否存在重名广告
                $where = [
                    'id' => ['NEQ', $post['id']],
                    'title' => trim($post['title']),
                ];
                if (Db::name('ad_position')->where($where)->count() > 0) $this->error('该广告名称已存在，请检查');
                // 修改广告主体信息
                $update = [
                    'id' => $post['id'],
                    'title' => trim($post['title']),
                    'type'  => !empty($post['type']) ? intval($post['type']) : 1,
                    'intro' => !empty($post['intro']) ? strval($post['intro']) : '',
                    'update_time' => $this->times,
                ];
                $resultID = Db::name('ad_position')->update($update);
            }

            if (!empty($resultID)) {
                $saveAll = [];
                // 图片类型
                if (1 === intval($post['type']) && !empty($post['img_litpic'])) {
                    $i = 1;
                    foreach ($post['img_litpic'] as $key => $value) {
                        if (!empty($value)) {
                            // 主键ID字段
                            $ad_id = !empty($post['img_id'][$key]) ? intval($post['img_id'][$key]) : 0;
                            // 添加参数
                            $saveData = [
                                // 主要参数
                                'id' => intval($ad_id),
                                'litpic' => preg_replace('/https:|http:|\s+/i', '', $value),
                                'title'  => !empty($post['img_title'][$key]) ? trim($post['img_title'][$key]) : '',
                                'links'  => !empty($post['img_links'][$key]) ? trim($post['img_links'][$key]) : '',
                                'intro'  => !empty($post['img_intro'][$key]) ? trim($post['img_intro'][$key]) : '',
                                'target' => !empty($post['img_target'][$key]) ? 1 : 0,
                                // 其他参数
                                'sort_order'  => $i++,
                                'update_time' => $this->times,
                            ];
                            if (!empty($ad_id)) {
                                $saveAll[$key] = $saveData;
                            } else {
                                // 删除主键ID字段
                                unset($saveData['id']);
                                // 添加参数
                                $saveAll[$key] = array_merge([
                                    // 主要参数
                                    'pid' => intval($post['id']),
                                    // 其他参数
                                    'media_type' => 1,
                                    'admin_id'   => session('admin_id'),
                                    'add_time'   => $this->times
                                ], $saveData);
                            }
                        }
                    }
                }
                // 媒体类型
                else if (2 === intval($post['type']) && !empty($post['video_litpic'])) {
                    // 添加参数
                    $saveData = [
                        // 主要参数
                        'id' => intval($post['video_id']),
                        'litpic' => preg_replace('/https:|http:|\s+/i', '', $post['video_litpic']),
                        'title'  => !empty($post['title']) ? trim($post['title']) : '',
                        'links'  => '',
                        'intro'  => '',
                        'target' => 0,
                        // 其他参数
                        'sort_order'  => 1,
                        'update_time' => $this->times,
                    ];
                    if (!empty($post['video_id'])) {
                        $saveAll[] = $saveData;
                    } else {
                        // 删除主键ID字段
                        unset($saveData['id']);
                        // 添加参数
                        $saveAll[] = array_merge([
                            // 主要参数
                            'pid' => intval($pots['id']),
                            // 其他参数
                            'media_type' => 2,
                            'admin_id'   => session('admin_id'),
                            'add_time'   => $this->times
                        ], $saveData);
                    }
                }
                // HTML代码
                else if (3 === intval($post['type']) && !empty($post['html_intro'])) {
                    // 添加参数
                    $saveData = [
                        // 主要参数
                        'id' => intval($post['html_id']),
                        'litpic' => '',
                        'title'  => !empty($post['title']) ? trim($post['title']) : '',
                        'links'  => '',
                        'intro'  => !empty($post['html_intro']) ? trim($post['html_intro']) : '',
                        'target' => 0,
                        // 其他参数
                        'sort_order'  => 1,
                        'update_time' => $this->times,
                    ];
                    if (!empty($post['html_id'])) {
                        $saveAll[] = $saveData;
                    } else {
                        // 删除主键ID字段
                        unset($saveData['id']);
                        // 添加参数
                        $saveAll[] = array_merge([
                            // 主要参数
                            'pid' => intval($pots['id']),
                            // 其他参数
                            'media_type' => 3,
                            'admin_id'   => session('admin_id'),
                            'add_time'   => $this->times
                        ], $saveData);
                    }
                }

                // 批量保存更新
                $result = !empty($saveAll) ? model('Ad')->saveAll($saveAll) : false;
                if (!empty($result)) {
                    Cache::clear('ad');
                    adminLog('编辑广告：'. $post['title']);
                }
                $this->success("操作成功", url('Pc/avd_index'));
            } else {
                $this->error("操作失败");
            }
        }

        $assign_data = [];

        // 广告ID
        $id = input('id/d', 0);
        if (empty($id)) $this->error('广告不存在，请联系管理员！');

        // 广告位
        $field = Db::name('ad_position')->where(['id' => $id])->find();
        if (empty($field)) $this->error('广告不存在，请联系管理员！');
        switch ($field['type']) {
            case '1':
                $field['type_name'] = '图片';
                break;
            case '2':
                $field['type_name'] = '多媒体';
                break;
            case '3':
                $field['type_name'] = 'HTML代码';
                break;
        }
        $assign_data['field'] = $field;

        // 广告内容
        $ad_data = Db::name('ad')->where(['pid' => $id])->order('sort_order asc')->select();
        foreach ($ad_data as $key => $val) {
            if (1 == $val['media_type']) {
                $ad_data[$key]['litpic'] = get_default_pic($val['litpic']); // 支持子目录
            }
        }
        $assign_data['ad_data'] = $ad_data;

        // 视频类型
        $media_type = tpCache('global.media_type');
        $media_type = !empty($media_type) ? $media_type : config('global.media_ext');
        $media_type = str_replace(",", "|", $media_type);
        $assign_data['media_type'] = $media_type;

        // 系统最大上传视频的大小
        $assign_data['upload_max_filesize'] = upload_max_filesize();

        $this->assign($assign_data);
        return $this->fetch();
    }

    // 广告删除
    public function avd_del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if (IS_AJAX_POST && !empty($id_arr)) {
            foreach ($id_arr as $key => $val) {
                if (array_key_exists($val, $this->ad_position_system_id)) $this->error('系统预定义，不能删除');
            }
            $result = Db::name('ad_position')->where(['id' => ['IN', $id_arr]])->delete(true);
            if (!empty($result)) {
                Db::name('ad')->where(['pid' => ['IN', $id_arr]])->delete(true);
                Cache::clear('ad');
                adminLog('删除广告-id：'.implode(',', $id_arr));
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('参数有误');
        }
    }

    // 删除广告图片
    public function del_imgupload()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if (IS_AJAX_POST && !empty($id_arr)) {
            $result = Db::name('ad')->where(['id' => ['IN', $id_arr]])->delete(true);
            if (!empty($result)) {
                Cache::clear('ad');
                adminLog('删除广告-id：'.implode(',', $id_arr));
            }
        }
    }

    // 打开预览视频
    public function open_preview_video()
    {
        $video_litpic = input('post.video_litpic/s', '');
        if (!is_http_url($video_litpic)) $video_litpic = request()->domain() . handle_subdir_pic($video_litpic, 'media');
        $this->success('执行成功', $video_litpic);
    }
    
    //  友情链接
    public function links_index()
    {
        // 应用搜索条件
        $where = [];
        $param = input('param.');
        $keywords = input('keywords/s', '', 'trim');
        foreach (['keywords'] as $key) {
            if (!empty($param[$key])) {
                if ($key == 'keywords') {
                    $where['title'] = ['LIKE', "%{$keywords}%"];
                } else {
                    $where[$key] = ['eq', trim($param[$key])];
                }
            }
        }

        // 查询数据
        $count = Db::name('links')->where($where)->count('id');
        $pager = new Page($count, config('paginate.list_rows'));
        $list = Db::name('links')->where($where)->order('sort_order asc, id asc')->limit($pager->firstRow.','.$pager->listRows)->select();
        $this->assign('list', $list);
        $this->assign('pager', $pager);
        $this->assign('page', $pager->show());

        return $this->fetch();
    }

    // 添加友情链接
    public function links_add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            $post['title'] = trim($post['title']);
            $post['target'] = !empty($post['target']) ? 1 : 0;
            $post['nofollow'] = !empty($post['nofollow']) ? 1 : 0;
            $post['url'] = preg_replace('/(<|>|;|\(|\)|\!)/i', '', trim($post['url']));
            if (empty($post['url'])) {
                $this->error('请填写网址URL');
            } else if (filter_var($post['url'], FILTER_VALIDATE_URL) === false) {
                $this->error('请正确填写网址URL');
            }
            if (empty($post['title'])) $this->error('请填写网站名称');

            // 处理LOGO
            $is_remote = !empty($post['is_remote']) ? $post['is_remote'] : 0;
            $post['logo'] = 1 === intval($is_remote) ? trim($post['logo_remote']) : trim($post['logo_local']);

            // 存储数据
            $insert = [
                'typeid'  => empty($post['typeid']) ? 1 : $post['typeid'],
                'groupid' => empty($post['groupid']) ? 1 : $post['groupid'],
                'url'     => $post['url'],
                'add_time' => $this->times,
                'update_time' => $this->times,
            ];
            $insertID = Db::name('links')->insertGetId(array_merge($post, $insert));
            if (!empty($insertID)) {
                Cache::clear('links');
                adminLog('新增友情链接：' . $post['title']);
                $this->success("操作成功！");
            } else {
                $this->error("操作失败！");
            }
        }

        return $this->fetch();
    }

    // 编辑友情链接
    public function links_edit()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            if (empty($post['id'])) $this->error('ID丢失，刷新重试~');
            if (empty($post['title'])) $this->error('请填写网站名称');
            $post['id'] = intval($post['id']);
            $post['title'] = trim($post['title']);
            $post['target'] = !empty($post['target']) ? 1 : 0;
            $post['nofollow'] = !empty($post['nofollow']) ? 1 : 0;
            $post['url'] = preg_replace('/(<|>|;|\(|\)|\!)/i', '', trim($post['url']));
            if (empty($post['url'])) {
                $this->error('请填写网址URL');
            } else if (filter_var($post['url'], FILTER_VALIDATE_URL) === false) {
                $this->error('请正确填写网址URL');
            }

            // 处理LOGO
            $is_remote = !empty($post['is_remote']) ? $post['is_remote'] : 0;
            $post['logo'] = 1 === intval($is_remote) ? trim($post['logo_remote']) : trim($post['logo_local']);

            // 存储数据
            $update = [
                'typeid'  => empty($post['typeid']) ? 1 : $post['typeid'],
                'groupid' => empty($post['groupid']) ? 1 : $post['groupid'],
                'add_time' => $this->times,
                'update_time' => $this->times,
            ];
            $updateID = Db::name('links')->where(['id' => $post['id']])->cache(true, null, "links")->update(array_merge($post, $update));
            if (!empty($updateID)) {
                Cache::clear('links');
                adminLog('编辑友情链接：' . $post['title']);
                $this->success("操作成功！");
            } else {
                $this->error("操作失败！");
            }
        }

        $id = input('id/d');
        $info = Db::name('links')->where(['id' => $id])->find();
        if (empty($info)) $this->error('数据不存在，请联系管理员！');
        if (is_http_url($info['logo'])) {
            $info['is_remote'] = 1;
            $info['logo_remote'] = handle_subdir_pic($info['logo']);
        } else {
            $info['is_remote'] = 0;
            $info['logo_local'] = handle_subdir_pic($info['logo']);
        }
        $this->assign('info', $info);

        return $this->fetch();
    }

    /**
     * 删除友情链接
     */
    public function links_del()
    {
        if (IS_AJAX_POST) {
            $id_arr = input('del_id/a');
            $id_arr = eyIntval($id_arr);
            if(!empty($id_arr)){
                $where = [
                    'id' => ['IN', $id_arr]
                ];
                $result = Db::name('links')->field('title')->where($where)->select();
                $deleteID = Db::name('links')->where($where)->cache(true, null, "links")->delete(true);
                if (!empty($deleteID)) {
                    adminLog('删除友情链接：'.implode(',', get_arr_column($result, 'title')));
                    $this->success('删除成功');
                }
            }
        }
        $this->error('删除失败');
    }

    // 菜单列表
    public function menus_list()
    {
        $position_id = input('position_id/d', 2);
        $where = [
            'c.position_id' => intval($position_id),
        ];
        $nav_list = $this->navigationlogic->nav_list(0, 0, false, 0, $where, false);
        $this->assign('nav_list', $nav_list);
        $this->assign('position_id', $position_id);

        // 获取所有有子栏目的栏目id
        $parent_ids = Db::name('nav_list')->where([
                'parent_id' => ['gt', 0],
                'is_del'    => 0,
            ])->group('parent_id')->column('parent_id');
        $cookied_treeclicked =  json_decode(cookie('navigation-treeClicked-Arr'));
        empty($cookied_treeclicked) && $cookied_treeclicked = [];
        $all_treeclicked = cookie('navigation-treeClicked_All');
        empty($all_treeclicked) && $all_treeclicked = [];
        $tree = [
            'has_children'=>!empty($parent_ids) ? 1 : 0,
            'parent_ids'=>json_encode($parent_ids),
            'all_treeclicked'=>$all_treeclicked,
            'cookied_treeclicked'=>$cookied_treeclicked,
            'cookied_treeclicked_arr'=>json_encode($cookied_treeclicked),
        ];
        $this->assign('tree', $tree);

        // 分类最多级别
        $this->assign('arctype_max_level', intval(config('global.arctype_max_level')));

        return $this->fetch();
    }

    // 菜单增加
    public function menus_add()
    {
        $position_id = input('position_id/d', 2);

        if (IS_AJAX_POST) {
            $post = input('post.');
            if (!empty($post)) {
                if (empty($post['nav_name'])) $this->error("请填写菜单名称");
                if (empty($post['host_id']) || empty($post['link_id'])) $this->error("请设置跳转链接");
                // 如果有所属菜单则执行
                if (!empty($post['parent_id'])) {
                    $post['topid'] = Db::name('nav_list')->where('nav_id', $post['parent_id'])->getField('topid');
                    if (0 === intval($post['topid'])) $post['topid'] = $post['parent_id'];
                }
                $insert = [
                    'is_del' => 0,
                    'add_time' => $this->times,
                    'update_time' => $this->times,
                    'position_id' => intval($position_id)
                ];
                $insertID = Db::name('nav_list')->insertGetId(array_merge($post, $insert));
                if (!empty($insertID)) {
                    Cache::clear('nav_list');
                    adminLog('新增导航管理菜单：'.$data['nav_name']); // 写入操作日志
                    $this->success("添加成功");
                }
            }
            $this->error("操作失败");
        }
        
        $nav_id = input('nav_id/d', 0);
        // 全部导航菜单列表
        $assignData['navListHtml'] = $this->navigationlogic->getAllNavList($position_id, $nav_id);
        $assignData['nav_id'] = $assignData['topid'] = 0;
        if (!empty($nav_id)) {
            $assignData['nav_id'] = intval($nav_id);
            $assignData['topid'] = Db::name('nav_list')->where('nav_id', $nav_id)->getField('topid');
        }
        $this->assign($assignData);

        $position_name = Db::name('nav_position')->where('position_id', $position_id)->value('position_name');
        $this->assign('position_name', $position_name);

        $this->assign('position_id', $position_id);
        return $this->fetch();
    }

    // 菜单编辑
    public function menus_edit()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            $position_id = input('position_id/d', 2);
            if (!empty($post)) {
                if (empty($post['nav_name'])) $this->error("请填写菜单名称");
                if (empty($post['host_id']) || empty($post['link_id'])) $this->error("请设置跳转链接");
                // 如果有所属菜单则执行
                if (!empty($post['parent_id'])) {
                    $post['topid'] = Db::name('nav_list')->where('nav_id', $post['parent_id'])->getField('topid');
                    if (0 === intval($post['topid'])) $post['topid'] = $post['parent_id'];
                }
                $where = [
                    'nav_id' => $post['nav_id']
                ];
                $update = [
                    'is_del' => 0,
                    'update_time' => $this->times,
                    'position_id' => intval($position_id)
                ];
                $updateID = Db::name('nav_list')->where($where)->update(array_merge($post, $update));
                if (!empty($updateID)) {
                    adminLog('编辑导航管理菜单：'.$post['nav_name']); // 写入操作日志
                    $this->success("操作成功");
                }
            }
            $this->error("操作失败");
        }

        $nav_id = input('nav_id/d', 0);
        if (empty($nav_id)) $this->error("请选择导航");
        $field = 'a.*, b.position_name, c.typename, l.link_names';
        $navigList = Db::name('nav_list')
            ->field($field)
            ->alias('a')
            ->join('nav_position b', 'a.position_id = b.position_id', 'LEFT')
            ->join('arctype c', 'a.link_id = c.id', 'LEFT')
            ->join('applets_ad_link l', 'l.host_id = a.host_id && l.link_id = a.link_id', 'LEFT')
            ->where('a.nav_id', $nav_id)
            ->find();
        // dump($navigList);
        // exit;
        $navigList['nav_name'] = !empty($navigList['arctype_sync']) ? $navigList['typename'] : $navigList['nav_name'];
        $assignData['navigList'] = $navigList;

        // 全部导航菜单列表
        $assignData['navListHtml'] = $this->navigationlogic->getAllNavList($navigList['position_id'], $nav_id);

        $this->assign($assignData);

        return $this->fetch();
    }

    public function menus_del()
    {
        if (IS_AJAX_POST) {
            $level = input('level/d', 0);
            $nav_id = input('nav_id/d', 0);
            if (empty($nav_id)) $this->error('请选择要删除的分类');

            // 一级分类删除
            if (0 === intval($level)) {
                $where = [
                    'nav_id|topid' => intval($nav_id),
                ];
                $columnID = Db::name('nav_list')->where($where)->column('nav_id');
            }
            // 二级分类删除
            else if (1 === intval($level)) {
                $where = [
                    'nav_id|parent_id' => intval($nav_id),
                ];
                $columnID = Db::name('nav_list')->where($where)->column('nav_id');
            }
            // 三级分类删除
            else if (2 === intval($level)) {
                $columnID = [intval($nav_id)];
            }
            // 执行删除指定分类
            $where = [
                'nav_id' => ['IN', $columnID],
            ];
            $deleteID = Db::name('nav_list')->where($where)->delete(true);
            // 删除分类后续操作
            if (!empty($deleteID)) {
                $this->success('删除成功');
            }
            $this->error('删除失败');
        }
    }

    // 底部菜单
    public function menus_footer()
    {
        return $this->fetch();
    }
    // 菜单链接
    public function link()
    {
        return $this->fetch();
    }
    // 菜单链接文章列表
    public function link_article()
    {
        return $this->fetch();
    }
    // 菜单链接分类列表
    public function link_arctype()
    {
        return $this->fetch();
    }
    //  自定义变量
    public function variables_index()
    {
        return $this->fetch();
    }
    //  文章列表
    public function article_index()
    {
        return $this->fetch();
    }
    //  文章分类
    public function article_type()
    {
        return $this->fetch();
    }
}